package com.codemart.lanze.core.freemarker;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codemart.lanze.core.freemarker.utils.Freemarker;
import com.codemart.lanze.modules.cms.entity.Advert;
import com.codemart.lanze.modules.cms.entity.AdvertPosition;
import com.codemart.lanze.modules.cms.service.IAdvertPositionService;
import com.codemart.lanze.modules.cms.service.IAdvertService;

import freemarker.core.Environment;
import freemarker.ext.beans.ArrayModel;
import freemarker.ext.beans.BeanModel;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 广告列表指令
 *
 * @author jyk
 */
@Repository
public class DirectiveAdvertList implements TemplateDirectiveModel {

	@Autowired
	private IAdvertService advertService;

	@Autowired
	private IAdvertPositionService advertPositionService;

	/**
	 * @param map.advertPositionId:广告位ID
	 */
	@SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
	@Override
	public void execute(Environment env, Map map, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		Long advertPositionId = Freemarker.getLong(map, "advertPositionId");

		Freemarker.getInteger(map, "size");
		Advert advert = new Advert();
		advert.setAdvertPositionId(advertPositionId);
		List<Advert> adverts = advertService.list(new QueryWrapper<>());
		AdvertPosition advertPosition = advertPositionService.getById(advertPositionId);
		loopVars[0] = new ArrayModel(adverts.toArray(), new BeansWrapper());
		loopVars[1] = new BeanModel(advertPosition, new BeansWrapper());
		body.render(env.getOut());
	}

}
